﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using PlanningGIS.Statistics;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Framework;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;

namespace PlanningGIS.Statistics
{
    public partial class FrmSpecifyStat : Office2007Form 
    {
        private static string strConfig = Application.StartupPath +
                    (System.Configuration.ConfigurationManager.AppSettings.Get("Folder") == null || System.Configuration.ConfigurationManager.AppSettings.Get("Folder").Trim() == "" ? "" : ("\\" + System.Configuration.ConfigurationManager.AppSettings.Get("Folder"))) +
                    "\\Config\\StatConfig.xml";
        private List<StatLayer> pLyrs = null;
        private StatLayer pCurrentLyr = null;
        private SelectXZQ selectXZQ1 = null;
        private IApplication m_pApplication = null;
        private IMapControl3 m_pMapControl = null;
        private IElement m_pElementUserDraw;

        /// <summary>
        /// 选取的行政区域
        /// </summary>
        public IPolygon XZQGeometry
        {
            get 
            {
                IPolygon pPolygon = null;
                switch (tabControl1.SelectedTab.Text)
                {
                    case "自定区域":
                        pPolygon = selectFWX1.PolygonFWX;
                        break;
                    case "行政区域":
                        pPolygon = selectXZQ1.GetGeometry() as IPolygon;
                        break;
                    default:
                        break;
                }
                return pPolygon;
            }
        }

        public FrmSpecifyStat(IApplication pApplication,IMapControl3 pMapControl)
        {
            InitializeComponent();
            this.m_pApplication = pApplication;
            this.m_pMapControl = pMapControl;
        }

        private void FrmCustomStat_Load(object sender, EventArgs e)
        {
            if (!File.Exists(strConfig))
            {
                MsgHelper.ShowInfomationMsgbox("报表统计的配置文件不存在！");
                Close();
            }
            pLyrs = StatFactory.GetLayersByConfigxml(strConfig);
            if (pLyrs == null || pLyrs.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("报表统计配置文件为空或错误，请重新配置！");
                Close();
            }
            if (m_pMapControl == null || m_pMapControl.LayerCount == 0)
            {
                MsgHelper.ShowInfomationMsgbox("地图不能为空！");
                Close();
            }
            foreach (StatLayer plyr in pLyrs)
            {
                if (plyr.ReportNames == null || plyr.ReportNames.Count == 0)
                {
                    continue;
                }
                else if ((plyr.ReportNames.Count == 1) && !(plyr.ReportNames[0].Display))
                {
                    continue;
                }
                else
                {
                    cboLayer.Items.Add(plyr.Value);
                }
            }
            if (cboLayer.Items.Count > 0)
            {
                cboLayer.SelectedIndex = 0;
            }

            IHookHelper m_HookHelp = new HookHelperExClass();
            m_HookHelp.Hook = m_pApplication;
            selectFWX1.HookHelper = m_HookHelp;
            selectFWX1.selectAreaControl1.afterButtonOkShift1 += new AfterButtonOkShift(AfterButtonOkEvent);
            selectXZQ1 = new SelectXZQ();
            this.tabControlPanel2.Controls.Add(selectXZQ1);
            selectXZQ1.Dock = System.Windows.Forms.DockStyle.Fill;
            selectXZQ1.Location = new System.Drawing.Point(1,1);
            selectXZQ1.Size = new Size(233, 222);
            selectXZQ1.Name = "selectXZQ1";
            selectXZQ1.TabIndex = 3;
            selectXZQ1.HookHelper = m_HookHelp;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!Validator())
            {
                DialogResult = DialogResult.None;
                return;
            }

            //将需要统计的字段反应到相应的结构中
            pCurrentLyr.StatCodes.Clear();
            List<StatCode> codes = new List<StatCode>();
            for (int i = 0; i < tvwField.Nodes.Count; i++)
            {
                TreeNode pNode = tvwField.Nodes[i];
                StatCode pCode=pNode.Tag as StatCode;
                if (pNode.Checked)
                {
                    pCode.Check = true;
                }
                else
                {
                    pCode.Check = false;
                }
                codes.Add(pCode);
            }
            pCurrentLyr.StatCodes = codes;

            Hashtable pHash = null;
            if (cboReport.Text.Trim().Equals("植被统计扩展"))
            {
                FrmVegStatPara veg = new FrmVegStatPara();
                if (veg.ShowDialog() == DialogResult.OK)
                {
                    pHash = veg.Parameters;
                }
            }
            if (pCurrentLyr == null)
            {
                MsgHelper.ShowInfomationMsgbox("要素统计为空！");
                return;
            }
            IFeatureLayer pFeatureLayer = MapHelper.GetFirstLayer<IFeatureLayer>(m_pMapControl.Map, pCurrentLyr.Value);
            if (pFeatureLayer == null)
            {
                MsgHelper.ShowInfomationMsgbox("尚未找到" + pCurrentLyr.Value + "层，请先加载该层！");
                return;
            }

            bool isSuccess;
            FeatureStat pStat = new FeatureStat();
            pStat.FeatureClass = pFeatureLayer.FeatureClass;
            pStat.MapControl = m_pMapControl;
            if (cboReport.Text.Trim().Equals("植被统计扩展"))
            {
                isSuccess = pStat.Stat(XZQGeometry, pCurrentLyr, pLyrs, cboReport.Text.Trim(), pHash);
            }
            else
            {
                isSuccess = pStat.Stat(XZQGeometry, pCurrentLyr, cboReport.Text.Trim());
            }
            this.Close();



        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cboLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string text = cboLayer.Text.Trim();
            GetStatlayerByValue(text);
            cboReport.Items.Clear();
            if (pCurrentLyr.ReportNames != null)
            {
                foreach (ReportName name in pCurrentLyr.ReportNames)
                {
                    if (name.Display)
                    {
                        cboReport.Items.Add(name.Key );
                    }
                }
                if (cboReport.Items.Count > 0)
                {
                    cboReport.SelectedIndex = 0;
                }
            }
            tvwField.Nodes.Clear();
            if (pCurrentLyr.StatCodes != null)
            {
                foreach (StatCode code in pCurrentLyr.StatCodes)
                {
                    TreeNode pNode=tvwField.Nodes.Add(code.Value);
                    pNode.Tag = code;
                    if (code.Check)
                    {
                        pNode.Checked = true;
                    }
                    else
                    {
                        pNode.Checked = false;
                    }
                }
            }
            
        }

        private void GetStatlayerByValue(string text)
        {
            foreach (StatLayer lyr in pLyrs)
            {
                if (lyr.Value == text)
                {
                    pCurrentLyr = lyr;
                    return;
                }
            }
            pCurrentLyr = null;
        }

        private void tvwField_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ShowTreeContextmenu(sender as TreeView);
            }
        }

        private void ShowTreeContextmenu(TreeView pTree)
        {
            ContextMenuStrip tvwMenuStrip = new ContextMenuStrip();
            ToolStripMenuItem pSelAllTool = new ToolStripMenuItem("全选");
            pSelAllTool.Click += delegate(object sender1, EventArgs e1)
            {
                foreach (TreeNode pNode in pTree.Nodes)
                {
                    if (pNode.Checked == false)
                        pNode.Checked = true;
                }
            };
            ToolStripMenuItem pSelNoTool = new ToolStripMenuItem("全部不选");
            pSelNoTool.Click += delegate(object sender1, EventArgs e1)
            {
                foreach (TreeNode pNode in pTree.Nodes)
                {
                    if (pNode.Checked)
                        pNode.Checked = false;
                }
            };
            tvwMenuStrip.Items.AddRange(new ToolStripItem[]
                                                {
                                                    pSelAllTool,
                                                    pSelNoTool 
                                                });
            pTree.ContextMenuStrip = tvwMenuStrip;
        }

        //验证器
        private bool Validator()
        {
            string reportname = cboReport.Text.Trim();
            if (reportname == null || reportname.Length == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请选择统计类型！");
                return  false ;
            }

            switch (tabControl1.SelectedTab.Text)
            {
                case "自定区域":
                    if (selectFWX1.PolygonFWX == null || selectFWX1.PolygonFWX.IsEmpty )
                    {
                        MsgHelper.ShowInfomationMsgbox("请选择自定区域！");
                        return false ;
                    }
                    break;
                case "行政区域":
                    IGeometry pGeo=selectXZQ1.GetGeometry();
                    if (pGeo  == null || pGeo.IsEmpty )
                    {
                        MsgHelper.ShowInfomationMsgbox("请选择行政区域！");
                        return false ;
                    }
                    break;
                default:
                    return false ;
            }

            int num=0;
            for (int i = 0; i < tvwField.Nodes.Count; i++)
            {
                if (tvwField.Nodes[i].Checked)
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请选择统计字段！");
                return false; 
            }

            return true;
        }

        private void FrmSpecifyStat_FormClosed(object sender, FormClosedEventArgs e)
        {
            (m_pApplication as IFramework).Tool = null;
            //switch (tabControl1.SelectedTab.Text)
            //{
            //    case "自定区域":
            //        selectFWX1.Dispose();
            //        break;
            //    case "行政区域":
            //        selectXZQ1.Dispose();
            //        break;
            //    default:
            //        break;
            //}
            IActiveView pAV = (m_pApplication.Document as IMxDocument).ActiveView;
            IGraphicsContainer pGC = pAV as IGraphicsContainer;
            pGC.DeleteAllElements();
            pAV.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pAV.Extent);

        }
        /// <summary>
        /// 自定义范围控件画完之后调用的事件
        /// </summary>
        /// <param name="pGeom"></param>
        /// <param name="shift"></param>
        private void AfterButtonOkEvent(IGeometry pGeom, int shift)
        {
            (m_pApplication as IFramework).MapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics,null,  (m_pApplication as IFramework).MapControl.ActiveView.Extent);
            if (pGeom == null || pGeom.IsEmpty || pGeom is IPoint)
            {
                return;
            }
            try
            {
                if (pGeom is IEnvelope)
                {
                    pGeom = ((IEnvelope)pGeom).ToPolygon();
                }
                else if (pGeom is ICircularArc)
                {
                    IPolygon pPolygon = new PolygonClass();
                    ISegmentCollection pSegCollection = pPolygon as ISegmentCollection;
                    object missing = System.Type.Missing;
                    pSegCollection.AddSegment(pGeom as ISegment, ref missing, ref missing);
                    pPolygon.SpatialReference = pGeom.SpatialReference;
                    pGeom = pPolygon;
                }

                if (pGeom == null || pGeom.IsEmpty) return;

                Cursor = Cursors.Default;

                IPolygon pPolygonCustom = pGeom as IPolygon;
                GeometryUserDraw(pPolygonCustom);
            }
            catch (System.Exception)
            {

            }
            finally
            {
                this.WindowState = FormWindowState.Normal;
            }

        }
        ///// 画用户权限内的范围
        ///// </summary>
        ///// <param name="pPolyUserDraw"></param>
        private void GeometryUserDraw(IPolygon pPolyUserDraw)
        {
            if (pPolyUserDraw == null || pPolyUserDraw.IsEmpty) return; ;
            IPolyline pPolyline = pPolyUserDraw.ToPolyline();

            IRgbColor pRgbColor = new RgbColorClass();
            pRgbColor.Red = 255;
            pRgbColor.Green = 155;
            pRgbColor.Blue = 0;

            IActiveView pActiveView = (m_pApplication.Document as IMxDocument).ActiveView;
            IGraphicsContainer pGeoContainer = pActiveView as IGraphicsContainer;
            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass();
            ILineElement pLineElement = new LineElementClass();
            pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            pLineSymbol.Color = pRgbColor;
            pLineSymbol.Width = 3;
            pLineElement.Symbol = pLineSymbol;
            m_pElementUserDraw = pLineElement as IElement;
            m_pElementUserDraw.Geometry = pPolyline;
            pGeoContainer.AddElement(m_pElementUserDraw, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pActiveView.Extent);
        }
    }
}
